package com.boot.system.service.Impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.framework.constants.PageConstants;
import com.boot.framework.token.domain.LoginUser;
import com.boot.system.service.ISysIOnlineUserService;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author yangfan
 * @date 2024/3/8
 * @Description
 */
@Service
public class SysOnlineUserServiceImpl implements ISysIOnlineUserService {
    @Override
    public IPage<LoginUser> selectPage(Map<String, Object> params) {
        // 获取所有已登录的会话id
        List<String> sessionIdList = StpUtil.searchSessionId("", 0, -1, false);
        int total = sessionIdList.size();
        int pageNum = Integer.parseInt(String.valueOf(params.get(PageConstants.PAGE)));
        int pageSize = Integer.parseInt(String.valueOf(params.get(PageConstants.LIMIT)));
        List<String> sessionPage = StpUtil.searchSessionId("", (pageNum - 1) * pageSize, pageSize, false);
        List<LoginUser> list = new LinkedList<>();
        for (String sessionId : sessionIdList) {

            // 根据会话id，查询对应的 SaSession 对象，此处一个 SaSession 对象即代表一个登录的账号
            SaSession session = StpUtil.getSessionBySessionId(sessionId);
            // 查询这个账号都在哪些设备登录了，依据上面的示例，账号A 的 tokenSign 数量是 3，账号B 的 tokenSign 数量是 2
            LoginUser user = (LoginUser) session.get("user");
            list.add(user);
        }
        IPage<LoginUser> page = new Page<LoginUser>(pageNum, pageSize);
        page.setTotal(total);
        page.setRecords(list);
        return page;
    }
}
